#include "Common.h"
#include "lame.h"
#include "shared_ptr.hpp"

#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>

int const WAV_ID_RIFF = 0x52494646; /* "RIFF" */
int const WAV_ID_WAVE = 0x57415645; /* "WAVE" */
int const WAV_ID_FMT = 0x666d7420; /* "fmt " */
int const WAV_ID_DATA = 0x64617461; /* "data" */
const std::string EMPTY = "";
const uint32 WAV_HEADER_LEN = 44;
// const uint32 MAX_TEXT_BUF_LEN = 500;
using namespace std;

int readn(int32 fd, byte* buf, uint32 nbytes)
{
    if (fd < 0 || buf == NULL)
    {
        return -1;
    }

    int nleft = nbytes;
    while (nleft > 0)
    {
        // cout << "readn test: nleft = "<< nleft << ", nbytes = " << nbytes << endl;
        int nread = 0;
        if ((nread = read(fd, buf, nleft)) < 0)
        {
            if (errno == EINTR)
            {
                continue;
            }
            cout << "readn errno: " << errno << "; nread = " << nread << endl;
            return -2;
        }

        if (nread == 0)
        {
            break;
        }

        nleft -= nread;
        buf += nread;
    }

    return nbytes - nleft;
}

int writen(int32 fd, const byte* buf, uint32 nbytes)
{
    if (fd < 0 || buf == NULL)
    {
        return -1;
    }

    int nleft = nbytes;
    while (nleft > 0)
    {
        int nwrite = 0;
        if ((nwrite = write(fd, buf, nleft)) < 0)
        {
            return -2;
        }

        nleft -= nwrite;
        buf += nwrite;
    }

    return nbytes;
}

string GetIP(struct sockaddr_in* addr)
{
    const int IP_STR_LEN = 32;
    char ipStr[IP_STR_LEN];
    memset(ipStr, 0, IP_STR_LEN);

    return inet_ntop(AF_INET, (void*)(&(addr->sin_addr)), ipStr, IP_STR_LEN) != NULL
        ? string(ipStr)
        : EMPTY;

}

uint16 GetPort(struct sockaddr_in* addr)
{
    return ntohs(addr->sin_port);
}

Item::Item()
{
    memset(_data, 0, MAX_BUF_LEN);
    _dataLen = 0;
}

void Item::Init()
{
    memset(_data, 0, MAX_BUF_LEN);
    _dataLen = 0;
}
